<template>
  <div>
    <!-- 
      highlight-current	是否高亮当前选中节点，默认值是 false。	boolean
      load	加载子树数据的方法，仅当 lazy 属性为true 时生效	function(node, resolve)
      lazy  是否懒加载子节点，需与 load 方法结合使用	boolean

      node-click	节点被点击时的回调
      render-content	树节点的内容区的渲染 Function	  Function(h, { node, data, store }
      expand-on-click-node	是否在点击节点的时候展开或者收缩节点， 默认值为 true，如果为 false，则只有点箭头图标的时候才会展开或者收缩节点。	boolean
     -->
    <el-tree
      highlight-current
      :props="defaultProps"
      :load="loadNode"
      lazy
      @node-click="handleNodeClick"
      :render-content="renderContent"
    ></el-tree>

    <!-- 弹窗 -->
    <!-- 添加 -->
    <el-dialog
      title="添加子导航"
      :visible.sync="dialogContentAddVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-input type="text" v-model="addContent"></el-input>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogContentAddVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureContentAddHandle">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog
      title="修改导航"
      :visible.sync="dialogContentUpdateVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-input type="text" v-model="updateContent"></el-input>
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogContentUpdateVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureContentUpdateHandle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { contentList, contentAdd, contentUpdate, contentDel } from "@/api";
import { mapActions } from 'vuex'

export default {
  name: "AdvertNav",
  inject:["reload"],
  data() {
    return {
      addContent: '',
      updateContent: '',
      dialogContentAddVisible: false,
      dialogContentUpdateVisible: false,
      defaultProps: {
        children: "children",
        label: "name",
      },
      ContentData: {}
    };
  },
  methods: {
    ...mapActions("contentInfoModule",["asyncSetContentInfo"]),  //mapActions("模块名字",["actions的方法"])
    async loadNode(node, resolve) {
      if (node.level === 0) {
        try {
          const res = await contentList();
          return resolve(res.result);
        } catch (error) {
          console.log(error);
        }
      }
      if (node.level >= 1) {
        try {
          const res = await contentList({ id: node.data.pid });
          console.log(res);

          if (res.status == 200) {
            return resolve(res.result);
          } else {
            return resolve([]);
          }
        } catch (error) {
          console.log(error);
        }
      }
    },
    handleNodeClick(data) {
      // console.log(data);
      this.asyncSetContentInfo(data);
    },
    renderContent(h, { node, data, store }) { // eslint-disable-line no-unused-vars
      return h('span',{class:'custom-tree-node'},[
        h('span',node.label),
        h('span',[
          h('el-button',{
            props:{size:"mini",type:"text"},
            on:{
              click: ()=>{
                this.append(node, data)
              }
            }
          },'添加子导航'),
          h('el-button',{
            props:{size:"mini",type:"text"},
            on:{
              click: ()=>{
                this.update(node, data)
              }
            }
          },'修改'),
          h('el-button',{
            props:{size:"mini",type:"text"},
            on:{
              click: ()=>{
                this.remove(node, data)
              }
            }
          },'删除')
        ])
      ])
      
    },
    append(node, data){ // eslint-disable-line no-unused-vars
      this.ContentData = data;
      this.dialogContentAddVisible = true;
    }, 
    update(node, data){ // eslint-disable-line no-unused-vars
      this.ContentData = data;
      this.dialogContentUpdateVisible = true;
    }, 
    async remove(node, data){ // eslint-disable-line no-unused-vars
      try {
        const res = await contentDel({pid: data.pid});
        console.log(res);
        if(res.status === 200){
          console.log('删除成功！');
          this.reload();
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
        }else{
          console.log('删除失败...');
          this.$message({
            message: '删除失败...',
            type: 'error'
          });
        }
      } catch (error) {
        console.log(error);
      }
    }, 
    async sureContentAddHandle(){
      try {
        const res = await contentAdd({
          name: this.addContent,
          pid: this.ContentData.pid
        })
        console.log(res);
        if(res.status === 200){
          console.log('添加成功！');
          this.dialogContentAddVisible = false;
          this.reload();
          this.$message({
            message: '添加成功！',
            type: 'success'
          });
        }else{
          console.log('添加失败...');
          this.$message({
            message: '添加失败...',
            type: 'error'
          });
        }
      } catch (error) {
        console.log(error);
      }
    },
    async sureContentUpdateHandle(){
      try {
        const res = await contentUpdate({
          name: this.updateContent,
          pid: this.ContentData.pid
        })
        console.log(res);
        if(res.status === 200){
          console.log('修改成功！');
          this.dialogContentUpdateVisible = false;
          this.reload();
          this.$message({
            message: '修改成功！',
            type: 'success'
          });
        }else{
          console.log('修改失败...');
          this.$message({
            message: '修改失败...',
            type: 'error'
          });
        }
      } catch (error) {
        console.log(error);
      }
    },
    handleClose() {
      this.dialogContentAddVisible = false;
      this.dialogContentUpdateVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>